﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', "", 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', "", 'trim|required|xss_clean|callback_check_database');
   
   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.&nbsp; User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
	 //redirect('home', 'location', 301);
	$data['login']=$this->session->userdata('logged_in');
	if($data['login']['status']=='admin'){
						  header( 'Location: '.base_url().'index.php/admin' ); /// ไปยัง contorller Admin
	}else if($data['login']['status']=='teacher'){
				  header( 'Location: '.base_url().'index.php/users' ); /// ไปยัง contorller user
	}else{
		 $this->session->unset_userdata('logged_in');
 							  header( 'Location: '.base_url().'index.php/login' ); /// ไปยัง contorller A
		}
		
	
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.&nbsp; Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username,
		 'name' => $row->name,
         'lastname' => $row->lastname,
		 'status'=> $row->status
		 
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'ชื่อผู้ใช้ หรือ รหัสผ่าน ผิด');
     return false;
   }
 }
}
?>
